//
//  MSDoubleListFilterVC.m
//  SocietySale
//
//  Created by Mike on 16/11/28.
//  Copyright © 2016年 Mike. All rights reserved.
//

#define BackViewHeight         (SCREEN_HEIGHT-KNavBarHeight-160)

#import "MSDoubleListFilterVC.h"

@interface MSDoubleListFilterVC ()
@property UIView * backgroundView;
@property(nonatomic)UIView *tabbarCoverView;
@property (nonatomic, assign) float positionY;
@property (nonatomic, assign) float bgHeight;
//弹出的筛选列表的视图容器
@property UIView* contentView;
@property (nonatomic, strong) NSMutableArray    *leftDataArray;
@property (nonatomic, strong) NSMutableArray    *leftCodeArray;
@property (nonatomic, strong) NSMutableArray    *rightDataArray;    //
@property (nonatomic, strong) NSMutableArray    *rightCodeArray;
@property (nonatomic, strong) NSMutableArray    *rightStateArray;    //状态
@property (nonatomic, strong) NSMutableArray    *middleStateArray;    //状态
@property (nonatomic, assign) NSInteger lastIndex;
@property (nonatomic, assign) NSInteger rightIndex;
@property (nonatomic, assign) NSInteger leftSelectIndex;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UITableView *rightTableView;
@property (nonatomic, copy) NSString *proviceCode;
@property (nonatomic, copy) NSString *cityCode;
@property (nonatomic, copy) NSString *proviceName;
@property (nonatomic, copy) NSString *cityName;
@end

@implementation MSDoubleListFilterVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    _positionY = 160;
    _bgHeight = SCREEN_HEIGHT-KNavBarHeight-_positionY;
    
    self.view.frame = CGRectMake(0, 0, 0.01, 0.01);
    //灰色背景
    self.backgroundView=[[UIView alloc] init];
    self.backgroundView.frame = CGRectMake(0, _positionY + KNavBarHeight, SCREEN_WIDTH, _bgHeight);
    self.backgroundView.backgroundColor=[UIColor colorWithWhite:0.f alpha:0.4f];
    self.backgroundView.clipsToBounds = YES;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)];
    tapGesture.delegate = (id)self;
    [self.backgroundView addGestureRecognizer:tapGesture];
    self.view.clipsToBounds=YES;
    self.view.backgroundColor=[UIColor clearColor];
    
    self.tableView = [self creatTableViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH/2, _bgHeight-44+KTabBarHeight)];
    self.tableView.tag = 10;
    
    self.rightTableView = [self creatTableViewWithFrame:CGRectMake(SCREEN_WIDTH/2, 0, SCREEN_WIDTH/2, _bgHeight-44+KTabBarHeight)];
    self.rightTableView.tag = 20;
    
    _lastIndex = -1;
    _rightIndex = -1;
    _leftSelectIndex = -1;
    _proviceCode = @"";
    _cityCode = @"";
    _proviceName = @"";
    _cityName = @"";
}

- (void)setDataArray:(NSArray *)dataArray{
    _dataArray = dataArray;
    self.leftDataArray = [[NSMutableArray alloc] initWithCapacity:0];
    self.leftCodeArray = [[NSMutableArray alloc] initWithCapacity:0];
    self.stateArray = [[NSMutableArray alloc] initWithCapacity:0];
    self.rightStateArray = [[NSMutableArray alloc] initWithCapacity:0];
    self.middleStateArray = [[NSMutableArray alloc] initWithCapacity:0];
    
    for (int i = 0; i< dataArray.count; i++){
        NSDictionary *dict = dataArray[i];
        [self.leftDataArray addObject:[dict allKeys][0]];
        
        NSDictionary *codeDict = self.codeArray[i];
        [self.leftCodeArray addObject:[codeDict allKeys][0]];
    }
    
    for (int i = 0; i< self.leftDataArray.count; i++){
        [self.stateArray addObject:@"NO"];
    }
    [self.tableView reloadData];
}

- (UITableView*)creatTableViewWithFrame:(CGRect)frame{
    UITableView *tableView = [[UITableView alloc] init];
    tableView.frame = frame;
    tableView.delegate = (id)self;
    tableView.dataSource = (id)self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.backgroundView addSubview:tableView];
    return tableView;
}

- (void)showInView:(float)topY
{
    _positionY = topY;
    _bgHeight = SCREEN_HEIGHT-KNavBarHeight-_positionY;
    self.backgroundView.frame = CGRectMake(0, _positionY + KNavBarHeight, SCREEN_WIDTH, _bgHeight);
    
    float height = _bgHeight-160;//MIN(self.tableView.contentSize.height, _bgHeight-160);
    self.tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH/2, height);
    self.rightTableView.frame = CGRectMake(SCREEN_WIDTH/2, 0, SCREEN_WIDTH/2, height);
//    self.tableView.height = _bgHeight-44+KTabBarHeight;
//    self.rightTableView.height = _bgHeight-44+KTabBarHeight;
    if (!self.backgroundView.superview) {
        [_backgroundView addSubview:self.view];
        UIWindow *window = [UIApplication sharedApplication].windows[0];
//        [window addSubview:self.tabbarCoverView];
        [window addSubview:self.backgroundView];
    }
}

- (void)showInBelowView{
    self.backgroundView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    self.tableView.frame = CGRectMake(0, SCREEN_HEIGHT-240, SCREEN_WIDTH/2, 240);
    self.rightTableView.frame = CGRectMake(SCREEN_WIDTH/2, SCREEN_HEIGHT-240, SCREEN_WIDTH/2, 240);

    if (!self.backgroundView.superview) {
        [_backgroundView addSubview:self.view];
        UIWindow *window = [UIApplication sharedApplication].windows[0];
        //        [window addSubview:self.tabbarCoverView];
        [window addSubview:self.backgroundView];
    }
}

- (void)dismiss
{
    if ([self.delegate respondsToSelector:@selector(selectedAreaProviceCode:cityCode:isTap:)]) {
        [self.delegate selectedAreaProviceCode:@{_proviceName:_proviceCode} cityCode:@{_cityName:_cityCode} isTap:YES];
    }
    [self.tabbarCoverView removeFromSuperview];
    [self.backgroundView removeFromSuperview];
    [self.view removeFromSuperview];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView.tag == 10) {
        return self.leftDataArray.count;
    }
    if (tableView.tag == 20) {
        return self.rightDataArray.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 10) {
        NSString *cellId = @"cellId";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.contentView.backgroundColor = [UIColor whiteColor];
        }
        cell.textLabel.text = self.leftDataArray[indexPath.row];
        cell.textLabel.font = HeitiFont(15);
        cell.textLabel.textColor = kLightBlackColor;
        cell.contentView.backgroundColor = [self.stateArray[indexPath.row] isEqualToString:@"YES"]?kDefaultViewBackgroundColor:[UIColor whiteColor];
        return cell;
    }
    if (tableView.tag == 20) {
        NSString *cellId = @"rightCellId";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.contentView.backgroundColor = kDefaultViewBackgroundColor;
        }
        cell.textLabel.text = self.rightDataArray[indexPath.row];
        cell.textLabel.font = HeitiFont(15);
//        cell.textLabel.textColor = kLightBlackColor;
        cell.textLabel.textColor = [self.rightStateArray[indexPath.row] isEqualToString:@"YES"]?kBlueColor:kLightBlackColor;
        return cell;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 10) {
        if (_lastIndex != -1) {
            UITableViewCell *lastCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_lastIndex inSection:0]];
            lastCell.contentView.backgroundColor = [UIColor whiteColor];
            [self.stateArray replaceObjectAtIndex:_lastIndex withObject:@"NO"];
        }
        
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.contentView.backgroundColor = kDefaultViewBackgroundColor;
        NSString *stateStr = [self.stateArray[indexPath.row] isEqualToString:@"NO"] ? @"YES":@"NO";
        [self.stateArray replaceObjectAtIndex:indexPath.row withObject:stateStr];
        
        NSDictionary *dict = self.dataArray[indexPath.row];
        self.rightDataArray = [[dict allValues] objectAtIndex:0];
        
        NSDictionary *codeDict = self.codeArray[indexPath.row];
        self.rightCodeArray = [[codeDict allValues] objectAtIndex:0];

        if (_lastIndex == indexPath.row) {//不是第一次，点击的同一个
            
        }
        else{
            if (_lastIndex != -1) {//不是第一次，不是同一个
                if (_leftSelectIndex == indexPath.row) {//点击的选择过的
                    [self.rightStateArray removeAllObjects];
                    for (int i = 0; i< self.middleStateArray.count; i++){
                        NSString *tempStr = self.middleStateArray[i];
                        if ([tempStr isEqualToString:@"YES"]) {
                            [self.rightStateArray addObject:@"YES"];
                        }
                        else{
                            [self.rightStateArray addObject:@"NO"];
                        }
                    }
                    [self.rightTableView reloadData];
                }
                else{//右边未选择过
                    [self.rightStateArray removeAllObjects];
                    for (int i = 0; i< self.rightDataArray.count; i++){
                        [self.rightStateArray addObject:@"NO"];
                    }
                    [self.rightTableView reloadData];
                }
            }
            else{//第一次
                for (int i = 0; i< self.rightDataArray.count; i++){
                    [self.rightStateArray addObject:@"NO"];
                }
                [self.rightTableView reloadData];
            }
        }
//        
//        [self.rightStateArray removeAllObjects];
//        for (int i = 0; i< self.rightDataArray.count; i++){
//            [self.rightStateArray addObject:@"NO"];
//        }
//        [self.rightTableView reloadData];
        
        _lastIndex = indexPath.row;

        _proviceCode = [[codeDict allKeys] objectAtIndex:0];
        _proviceName = self.leftDataArray[indexPath.row];
        if (self.rightCodeArray.count<1) {
            [self.tabbarCoverView removeFromSuperview];
            [self.backgroundView removeFromSuperview];
            [self.view removeFromSuperview];
            _cityCode = @"";
            _cityName = @"";
            if ([self.delegate respondsToSelector:@selector(selectedAreaProviceCode:cityCode:isTap:)]) {
                [self.delegate selectedAreaProviceCode:@{_proviceName:_proviceCode} cityCode:@{_cityName:_cityCode} isTap:NO];
            }
        }
    }
    if (tableView.tag == 20) {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        
        if (_leftSelectIndex != _lastIndex) {
            _rightIndex = -1;
        }
        if (_rightIndex != -1) {
            UITableViewCell *lastCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_rightIndex inSection:0]];
            if (indexPath.row == _rightIndex) {
                NSString *stateStr = [self.rightStateArray[indexPath.row] isEqualToString:@"NO"] ? @"YES":@"NO";
                [self.rightStateArray replaceObjectAtIndex:indexPath.row withObject:stateStr];
                cell.textLabel.textColor = [stateStr isEqualToString:@"YES"]? kBlueColor:kLightBlackColor;
            }
            else{
                [self.rightStateArray replaceObjectAtIndex:_rightIndex withObject:@"NO"];
                [self.rightStateArray replaceObjectAtIndex:indexPath.row withObject:@"YES"];
                lastCell.textLabel.textColor = kLightBlackColor;
                cell.textLabel.textColor = kBlueColor;
            }
        }
        else{
            NSString *stateStr = [self.rightStateArray[indexPath.row] isEqualToString:@"NO"] ? @"YES":@"NO";
            [self.rightStateArray replaceObjectAtIndex:indexPath.row withObject:stateStr];
            cell.textLabel.textColor = [stateStr isEqualToString:@"YES"]? kBlueColor:kLightBlackColor;
        }
        
        [self.middleStateArray removeAllObjects];
        for (int i = 0; i< self.rightStateArray.count; i++){
            NSString *tempStr = self.rightStateArray[i];
            if ([tempStr isEqualToString:@"YES"]) {
                [self.middleStateArray addObject:@"YES"];
            }
            else{
                [self.middleStateArray addObject:@"NO"];
            }
        }
        
        _leftSelectIndex = _lastIndex;
        
        _rightIndex = indexPath.row;
        _cityCode = self.rightCodeArray[indexPath.row];
        if ([self.middleStateArray[indexPath.row] isEqualToString:@"YES"]) {
            _cityName = self.rightDataArray[indexPath.row];
        }
        else{
            _cityName = @"";
        }
        [self.tabbarCoverView removeFromSuperview];
        [self.backgroundView removeFromSuperview];
        [self.view removeFromSuperview];
        if ([self.delegate respondsToSelector:@selector(selectedAreaProviceCode:cityCode:isTap:)]) {
            [self.delegate selectedAreaProviceCode:@{_proviceName:_proviceCode} cityCode:@{_cityName:_cityCode} isTap:NO];
        }
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    CGPoint touchPoint = [touch locationInView:self.backgroundView];
    if (CGRectContainsPoint(self.tableView.frame, touchPoint) || CGRectContainsPoint(self.rightTableView.frame, touchPoint)) {
        return NO;
    }
    return YES;
}

//- (UIView *)tabbarCoverView
//{
//    if (!_tabbarCoverView) {
//        _tabbarCoverView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREENFRAME.size.height-KTabBarHeight, SCREEN_WIDTH, KTabBarHeight)];
//        _tabbarCoverView.backgroundColor = [UIColor colorWithWhite:0.f alpha:0.4f];
//        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)];
//        [_tabbarCoverView addGestureRecognizer:tapGesture];
//    }
//    return _tabbarCoverView;
//}


@end
